package com.cs.pk.actions;

import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowPulldownDelegate;
import org.eclipse.ui.PlatformUI;

import com.cs.pk.Activator;
import com.cs.pk.job.BuildJob;
import com.cs.pk.job.LocalBuildJob;
import com.cs.pk.utils.interfaces.ListModificationListener;

public class Build implements IWorkbenchWindowPulldownDelegate,
	ListModificationListener {

    private Menu buildMenu = null;
    private Menu local, remote = null;

    public Menu getMenu(final Control parent) {
	parent.setData("Control");
	if (buildMenu == null) {
	    buildMenu = new Menu(parent);
	    MenuItem localItems = new MenuItem(buildMenu,SWT.CASCADE);
	    localItems.setText("Local..");
	    local = new Menu(buildMenu);
	    localItems.setMenu(local);
	    List buildItems = Activator.getDefault().localBuildItems;
	    for (Iterator iterator = buildItems.iterator(); iterator.hasNext();) {
		String object = (String) iterator.next();
		MenuItem item = new MenuItem(local, SWT.PUSH);
		item.setText(object);
		item.setData(object);
		item.addSelectionListener(new SelectionAdapter() {
		    public void widgetSelected(SelectionEvent e) {
			MenuItem item = (MenuItem) e.getSource();
						final BuildJob bj = new LocalBuildJob(item.getText());
						bj.addJobChangeListener(new JobChangeAdapter() {
							public void done(IJobChangeEvent event) {
								if (event.getResult().isOK())
									bj.showMessage();
								else
									bj.showErrorMessage();
							}
						});
						bj.schedule(Job.BUILD);
					}

		});
	    }
	    
	    MenuItem remoteItems = new MenuItem(buildMenu,SWT.CASCADE);
	    remoteItems.setText("Remote..");
	    
	    remote = new Menu(buildMenu);
            remoteItems.setMenu(remote);
	    buildItems = Activator.getDefault().remoteBuildItems;
	    for (Iterator iterator = buildItems.iterator(); iterator.hasNext();) {
		String object = (String) iterator.next();
		MenuItem item = new MenuItem(remote, SWT.PUSH);
		item.setText(object);
		item.setData(object);
		item.addSelectionListener(new SelectionAdapter() {
		    public void widgetSelected(SelectionEvent e) {
			MenuItem item = (MenuItem) e.getSource();
		    }

		});
	    }
	    
	    Separator separator = new Separator();
	    separator.fill(buildMenu, 2);
	    MenuItem configuration = new MenuItem(buildMenu,SWT.PUSH);
	    configuration.setText("Build Configuration..");
            configuration.setImage(Activator.getImageDescriptor("icons/build.gif").createImage());
            configuration.addSelectionListener(new SelectionListener(){

		public void widgetDefaultSelected(SelectionEvent e) {
		    
		}

		public void widgetSelected(SelectionEvent e) {
                  LaunchConfigurationForm.launchForm(null, parent.getShell(), Activator.getImageDescriptor("icons/build.gif").createImage());		    
		}
        	
            });

	}
	return buildMenu;
    }

    public void dispose() {
	if (buildMenu != null) {
	    buildMenu.dispose();
	}
    }

    public void init(IWorkbenchWindow window) {
	Activator.getDefault().localBuildItems
		.registerListModificationListener(this);
	Activator.getDefault().remoteBuildItems
	.registerListModificationListener(this);
    }

    public void run(IAction action) {
    }

    public void selectionChanged(IAction action, ISelection selection) {

    }

    public void modified(final int addOrRemove,final Object event,final String name) {
	
	PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable(){
	
	public void run(){
	if (buildMenu != null) {
	    if (event != null) {
		if (addOrRemove == ListModificationListener.REMOVEITEM) {
		    MenuItem items[] = null;
		    if("local".equals(name)){
			items = local.getItems();
		    }else{
			items = remote.getItems();
		    }
		    for (int i = 0; i < items.length; i++) {
			MenuItem item = items[i];
			if (event.toString().equals(item.getData())) {
			    item.dispose();
			    break;
			}
		    }
		} else {
		   
		    MenuItem item = null;
		    if("local".equals(name)){
			item = new MenuItem(local, SWT.PUSH);
		    }else{
			item = new MenuItem(remote, SWT.PUSH);
		    }
		    item.setText(event.toString());
		    item.setData(event.toString());
		    item.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
			    MenuItem item = (MenuItem) e.getSource();
			}

		    });
		}
	    }
	}
	
	}
	});
    }
    // private boolean echoOff = false;
    // private boolean overLan = false;
    //
    // public void dispose() {
    //
    // }
    //
    // public void init(IWorkbenchWindow window) {
    //
    // }
    //
    // public void run(IAction action) {
    // // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
    // // public void run() {
    // try {
    // System.out.println("prabhatk: "+this.getClass().getName()+" "+"Starting ");
    // startBuilding();
    // System.out.println("prabhatk: "+this.getClass().getName()+" "+"ending ");
    // } catch (IOException e) {
    // e.printStackTrace();
    // } catch (InterruptedException e) {
    // e.printStackTrace();
    // }
    // // }
    // // });
    // }
    //
    // private void startBuilding() throws IOException, InterruptedException {
    // Process process;
    // ProcessBuilder builder = null;
    //
    // builder = new ProcessBuilder(new String[] { "cmd.exe" });
    // process = builder.start();
    //
    // OutputStream os = process.getOutputStream();
    //
    // StreamReader errorReader = new
    // StreamReader(process.getErrorStream(),"ERROR",true);
    // StreamReader inputReader = new
    // StreamReader(process.getInputStream(),"INPUT",true);
    // errorReader.start();
    // inputReader.start();
    //
    // if (echoOff)
    // os.write("@echo off\n".getBytes());
    // os.flush();
    // if (!overLan) {
    // localBuild(os);
    // }
    //        
    // // os.write("M:\n".getBytes());
    // // os
    // //
    // .write("cd M:/Prabhatk_GETPVR_VOD_MOR_Releases_2/MHC_BUILD/MHC_BuildTree\n"
    // // .getBytes());
    // // // cygwinFileReading(os);
    // // os.write("export VOD=on\n".getBytes());
    // // os.write("export PDL=off\n".getBytes());
    // // os.write("./make_mor release gtpkb1 VOD=on PDL=off\n".getBytes());
    // os.flush();
    // os.close();
    //
    // process.waitFor();
    //
    // errorReader.dispose();
    // inputReader.dispose();
    // }
    //
    // private void localBuild(OutputStream os) throws IOException {
    // String root = "F:/";//Util.getValues(Constants.BUILD_ROOT_DIR);
    // String buildRoot ="cd "+
    // root+"/MHC_BUILD/MHC_BuildTree\n";//Util.getValues(Constants.BUILD_PATH);
    // char drive = root.charAt(0);
    // os.write(new String(drive+":\n").getBytes());
    // os.flush();
    // os.write(buildRoot.getBytes());
    // os.flush();
    //		
    // String cygCommands =readDefaultCommands();//
    // Util.getValues(Constants.BUILD_COMPLETE_CMD);
    // if(cygCommands!=null && !cygCommands.trim().equals("")) {
    // String arg[] = cygCommands.split("\n");
    // writeToOutput(os, arg);
    // }
    //		
    // String arguments =
    // "export VOD=on;export PDL=off\n";//Util.getValues(Constants.BUILD_ENV_VARIABLE);
    // if(arguments!=null &&
    // /*!arguments.trim().equals(Activator.getDefault().getDefaultPreference(Constants.BUILD_ENV_VARIABLE))
    // &&*/ !arguments.trim().equals("")) {
    // String arg[] = arguments.split(";");
    // writeToOutput(os, arg);
    // }
    //		
    //		
    // String command =
    // "./make_mor release gtpkb1 VOD=on PDL=off\n";//Util.getValues(Constants.BUILD_COMMAND)+"\n";
    // os.write(command.getBytes());
    // }
    //	
    // private String readDefaultCommands() throws IOException {
    // InputStream is = new FileInputStream(new
    // File("D:/workspace/codestriker/buildcommands.properties"));//pluginBundle.getEntry("/buildcommands.properties").openStream();
    // StringBuffer sb = new StringBuffer();
    // byte b[] = new byte[512];
    // int n = 0;
    // while((n=is.read(b))>-1){
    // sb.append(new String(b,0,n));
    // b = new byte[512];
    // }
    // is.close();
    // //defaultPreference.put(Constants.BUILD_COMPLETE_CMD, sb.toString());
    // return sb.toString();
    // }
    //
    // private void writeToOutput(OutputStream os, String arg[])
    // throws IOException {
    // for (int i = 0; i < arg.length; i++) {
    // if (arg[i].trim().equals("")) {
    // continue;
    // }
    // os.write((arg[i] + "\n").getBytes());
    // os.flush();
    // }
    // }
    //
    // public void selectionChanged(IAction action, ISelection selection) {
    //                
    // }
    //	
    // public static void main(String args[]) {
    // new Build().run(null);
    // }

//    public Menu getMenu(Menu parent) {
//	    System.out.println(parent.getData());
//	return parent;
//    }

}
